<template>
  <div class="admin-page-wrapper">
    <div class="admin-stats">
      <el-card>
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
          <span style="font-size: 20px; font-weight: bold;">知途</span>
          <el-button type="primary" @click="$router.push('/admin/posts')">
            论坛帖子管理
          </el-button>
        </div>
        <div class="header-bar">
          <h2>论坛活跃度统计</h2>
          <div class="admin-info">
            <el-avatar
              v-if="user && user.avatar"
              :src="user.avatar"
              size="small"
              style="margin-right: 8px;"
            />
            <el-dropdown>
              <span class="el-dropdown-link">
                {{ user.username || '管理员' }}
                <el-icon><arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <!-- <div class="header-bar"> -->
          <!-- <span class="stats-title">论坛活跃度统计</span>
          <el-button type="primary" @click="$router.push('/admin/posts')">
            论坛帖子管理
          </el-button>
        </div> -->
        <div class="filter-bar">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="fetchActivity(1)"
          />
        </div>
        <div class="stats-content">
          <div class="table-area">
            <el-table :data="activityList" @sort-change="handleSort" border>
              <el-table-column prop="username" label="用户名" sortable />
              <el-table-column prop="postCount" label="发帖数" sortable />
              <el-table-column prop="replyCount" label="回帖数" sortable />
              <el-table-column prop="totalActivity" label="总活跃度" sortable />
            </el-table>
            <el-pagination
              v-if="total > 0"
              background
              layout="prev, pager, next, jumper, ->, total"
              :current-page="page"
              :page-size="size"
              :total="total"
              @current-change="fetchActivity"
            />
          </div>
          <div class="chart-area">
            <div ref="chartRef" class="chart-box"></div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from 'vue'
import { getUserActivity } from '../api/post'
import * as echarts from 'echarts'
import { useUserStore } from '../store/user'
import { ArrowDown } from '@element-plus/icons-vue'

const userStore = useUserStore()
const user = userStore.user || {}

const dateRange = ref([])
const activityList = ref([])
const page = ref(1)
const size = ref(10)
const total = ref(0)
const sortProp = ref('totalActivity')
const sortOrder = ref('descending')
const chartRef = ref(null)
let chartInstance = null

function fetchActivity(newPage = 1) {
  if (dateRange.value.length === 2) {
    page.value = newPage
    getUserActivity({
      start: dateRange.value[0],
      end: dateRange.value[1],
      page: page.value - 1, // 后端从0开始
      size: size.value
    }).then(res => {
      const records = res.data.data.records || []
      activityList.value = records.map(item => ({
        ...item,
        totalActivity: (item.postCount || 0) + (item.replyCount || 0)
      }))
      total.value = res.data.data.total
      sortActivityList()
      renderChart()
    })
  }
}

function handleSort({ prop, order }) {
  sortProp.value = prop
  sortOrder.value = order
  sortActivityList()
  renderChart()
}

function sortActivityList() {
  if (!sortProp.value) return
  activityList.value.sort((a, b) => {
    const valA = a[sortProp.value] || 0
    const valB = b[sortProp.value] || 0
    if (sortOrder.value === 'ascending') {
      return valA - valB
    } else {
      return valB - valA
    }
  })
}

function renderChart() {
  if (!chartRef.value) return
  if (!chartInstance) {
    chartInstance = echarts.init(chartRef.value)
  }
  const usernames = activityList.value.map(item => item.username)
  const postCounts = activityList.value.map(item => item.postCount)
  const replyCounts = activityList.value.map(item => item.replyCount)
  const totalActivity = activityList.value.map(item => item.totalActivity)

  chartInstance.setOption({
    tooltip: { trigger: 'axis' },
    legend: { data: ['发帖数', '回帖数', '总活跃度'] },
    xAxis: { type: 'category', data: usernames },
    yAxis: { type: 'value' },
    series: [
      {
        name: '发帖数',
        type: 'bar',
        data: postCounts
      },
      {
        name: '回帖数',
        type: 'bar',
        data: replyCounts
      },
      {
        name: '总活跃度',
        type: 'line',
        data: totalActivity,
        smooth: true
      }
    ]
  })
}

watch(activityList, () => {
  nextTick(() => renderChart())
}, { deep: true })

onMounted(() => {
  renderChart()
  window.addEventListener('resize', () => {
    chartInstance && chartInstance.resize()
  })
})
</script>

<style scoped>
.admin-page-wrapper {
  min-height: 100vh;
  background: #ffffff;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding-left: 48px;
  padding-right: 48px;
  box-sizing: border-box;
}
.admin-stats {
  width: 100%;
  max-width: 1100px;
  margin: 1px auto 0 auto;
  background: linear-gradient(135deg, #b2f0e6 0%, #fbeee6 100%);
  /* background: #fff; */
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
  padding: 32px 32px 24px 32px;
  box-sizing: border-box;
}
.header-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}
.stats-title {
  font-size: 20px;
  font-weight: bold;
  color: #222;
  letter-spacing: 2px;
}
.filter-bar {
  background: linear-gradient(135deg, #b2f0e6 0%, #fbeee6 100%);
  /* background: #f7f8fa; */
  padding: 16px 20px;
  border-radius: 8px;
  margin-bottom: 24px;
  display: flex;
  align-items: center;
}
.stats-content {
  display: flex;
  gap: 24px;
  min-height: 420px;
}
.table-area {
  flex: 7;
  min-width: 0;
  display: flex;
  flex-direction: column;
}
.chart-area {
  flex: 5;
  min-width: 0;
  display: flex;
  align-items: center;
  justify-content: center;
}
.chart-box {
  width: 100%;
  height: 400px;
  /* background: #fff; */
  background: linear-gradient(135deg, #b2f0e6 0%, #fbeee6 100%);
  border-radius: 8px;
  box-shadow: 0 2px 8px #f0f1f2;
}
.admin-info {
  display: flex;
  align-items: center;
}
.el-dropdown-link {
  cursor: pointer;
  color: #409eff;
  font-weight: bold;
  display: flex;
  align-items: center;
}
@media (max-width: 1200px) {
  .admin-stats {
    max-width: 98vw;
    padding: 16px 8px;
  }
  .admin-page-wrapper {
    padding-left: 8px;
    padding-right: 8px;
  }
}
@media (max-width: 900px) {
  .stats-content {
    flex-direction: column;
  }
  .chart-area, .table-area {
    width: 100%;
    min-width: 0;
  }
  .chart-box {
    height: 300px;
  }
}
@media (max-width: 768px) {
  .admin-stats {
    max-width: 100vw;
    padding: 8px 2px;
  }
  .admin-page-wrapper {
    padding-left: 0;
    padding-right: 0;
  }
}
</style>
